package com.game.logic.user;

import com.coment.cfg.luban.constant.AIDCFG;
import com.coment.po.Game;
import com.coment.po.roles.Roles;
import com.coment.message.BloodVolumeSynchronizationMessage;
import com.game.dao.core.GameDao;
import com.game.dao.user.roles.RolesDao;
import com.game.framework.lock.LooksManager;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@Component
public class UserGameRolesDao {
    @Resource
    private GameDao gameDao;

    @Resource
    private RolesDao rolesDao;

    public boolean gameIsWin(@NotNull Integer anchorInfoId) {
        Game game = gameDao.findByIdMust(anchorInfoId);
        return game.monsterSet.stream()
                .map(rolesId -> rolesDao.findById(rolesId).orElse(null))
                .filter(Objects::nonNull)
                .noneMatch(Roles::isSurvive);
    }


    public BloodVolumeSynchronizationMessage survivalCharacter(@NotNull Integer anchorInfoId) {
        Game game = gameDao.findByIdMust(anchorInfoId);
        List<Roles> list = game.monsterSet.stream().map(rolesId -> {
            Roles byIdMust;
            ReentrantLock writeLock = LooksManager.getWriteLock(Roles.class, rolesId);
            writeLock.lock();
            try {
                byIdMust = rolesDao.findByIdMust(rolesId);
            } catch (Exception e) {
                byIdMust = null;
            } finally {
                writeLock.unlock();
            }
            return byIdMust;
        }).filter(Objects::nonNull).filter(Roles::isSurvive).toList();
        Map<String, Double> collect = list.stream().collect(Collectors.toMap(Roles::getId, roles -> roles.rolePanel.getAttribute().get(AIDCFG.hp)));
        return new BloodVolumeSynchronizationMessage(anchorInfoId, collect);
    }
}
